class TaskController < ApplicationController
  before_filter :app_login

  def index
    project = params[:project]

    start_date =  !params[:range].nil? ? params[:start_date] : Date.today.beginning_of_month
    end_date =  !params[:range].nil? ? params[:end_date] : Date.today.end_of_month
    person =  params[:person].nil? ? 0 : params[:person]

    projects = Project.joins(:tasks).where(:tasks => {:user_id => current_user }).
                  group('projects.id, projects.name').order('projects.id DESC').
                  select('projects.id, projects.name')

    tasks_query = Task

    # if project is nill show all, if 0 show tasks without a project 
    unless project.nil? || project.empty?
      puts 'project'
      if project.to_i > 0
        tasks_query = tasks_query.where({:project_id => project})
      else
        tasks_query = tasks_query.where('project_id is NULL')
      end
    end


    unless start_date.nil? || end_date.nil?
      tasks_query = tasks_query.where('created_at >= :start_date AND created_at <= :end_date',
                                      { :start_date => start_date, :end_date => end_date})
    end

    unless person.to_i == 0
      tasks_query = tasks_query.where(:user_id => person)
    end

    tasks = tasks_query.order(:created_at) .includes(:assigned_by, :user, :project).all
    company = User.includes(:company, { :company => :users }).find(current_user).company
    people = company.users unless company.nil?

    @tasks_view = { :project => project, :start_date => start_date,
        :end_date => end_date, :person => person, :tasks => tasks, :people => people, :projects => projects }
  end

  def toggle_status
    task_id = params[:id]
    task = Task.find(task_id)
    task.toggle_status()

    render :json => { :message => 'status updated.' }
  end

  def edit
    task = params[:task]

    puts task[:id]
    puts task[:name]
    puts task[:project][:name]
    puts task[:due_date]
    puts task[:user]
    puts task[:time_spent]

    task_found = Task.find(task[:id])
    task_found.edit(task[:name], task[:project][:name], task[:due_date], task[:user], current_user, task[:time_spent])

    render :json => { :message => 'task edited.' }
  end
end
